/*
 * @Descripttion: 工具集
 * @version: 1.2
 * @LastEditors: sakuya
 * @LastEditTime: 2022年5月24日00:28:56
 */

import CryptoJS from 'crypto-js';
import { nanoid } from 'nanoid';
import sysConfig from "@renderer/config";
import { ElLoading, ElMessage } from "element-plus"
import { client } from "../config/aliOSS";

const tool = {}

tool.oss = {
  upload(file, loading = true) {
    const uuid = nanoid();
    const index = file.name.lastIndexOf(".")
    const suffix = file.name.substring(index + 1)

    const currentDate = tool.dateFormat(new Date(), 'yyyy-MM-dd')

    let fileName = "xiaoluxian-crm/" + currentDate + "/" + uuid + "." + suffix //定义唯一的文件名，打印出来的uid其实就是时间戳

    const _loading = loading ? ElLoading.service({ lock: true }) : { close: noop }
    return client.multipartUpload(fileName, file)
      .then(data => ({
        url: this.endpoint() + data.name,
        fileEtags: data.name
      }))
      .catch(err => {
        ElMessage.error("上传失败")
        throw err
      }).finally(() => {
        _loading.close()
      })
  },
  file2Base64(file) {
    return new Promise((resolve, reject) => {
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (e) => {
        resolve(e.target.result);
      };
    });
  },
  download(){

  },
  endpoint() {// OSS访问域名。
    return "https://oss.xuexiluxian.cn/"
  }
}

/* localStorage */
tool.data = {
	set(key, data, datetime = 0) {
		//加密
		if(sysConfig.LS_ENCRYPTION == "AES"){
			data = tool.crypto.AES.encrypt(JSON.stringify(data), sysConfig.LS_ENCRYPTION_key)
		}
    let cacheValue = {
      content: data,
      datetime: parseInt(datetime) === 0 ? 0 : new Date().getTime() + parseInt(datetime) * 1000
    }
    return localStorage.setItem(key, JSON.stringify(cacheValue))
	},
	get(key) {
    try {
      const value = JSON.parse(localStorage.getItem(key))
      if (value) {
        let nowTime = new Date().getTime()
        if (nowTime > value.datetime && value.datetime != 0) {
          localStorage.removeItem(key)
          return null;
        }
        //解密
        if(sysConfig.LS_ENCRYPTION == "AES"){
          value.content = JSON.parse(tool.crypto.AES.decrypt(value.content, sysConfig.LS_ENCRYPTION_key))
        }
        return value.content
      }
      return null
    } catch (err) {
      return null
    }
	},
	remove(key) {
		return localStorage.removeItem(key)
	},
	clear() {
		return localStorage.clear()
	}
}

/*sessionStorage*/
tool.session = {
	set(table, settings) {
		var _set = JSON.stringify(settings)
		return sessionStorage.setItem(table, _set);
	},
	get(table) {
		var data = sessionStorage.getItem(table);
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data;
	},
	remove(table) {
		return sessionStorage.removeItem(table);
	},
	clear() {
		return sessionStorage.clear();
	}
}

/*cookie*/
tool.cookie = {
	set(name, value, config={}) {
		var cfg = {
			expires: null,
			path: null,
			domain: null,
			secure: false,
			httpOnly: false,
			...config
		}
		var cookieStr = `${name}=${escape(value)}`
		if(cfg.expires){
			var exp = new Date()
			exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000)
			cookieStr += `;expires=${exp.toGMTString()}`
		}
		if(cfg.path){
			cookieStr += `;path=${cfg.path}`
		}
		if(cfg.domain){
			cookieStr += `;domain=${cfg.domain}`
		}
		document.cookie = cookieStr
	},
	get(name){
		var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"))
		if(arr != null){
			return unescape(arr[2])
		}else{
			return null
		}
	},
	remove(name){
		var exp = new Date()
		exp.setTime(exp.getTime() - 1)
		document.cookie = `${name}=;expires=${exp.toGMTString()}`
	}
}

/* Fullscreen */
tool.screen = function (element) {
	var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
	if(isFull){
		if(document.exitFullscreen) {
			document.exitFullscreen();
		}else if (document.msExitFullscreen) {
			document.msExitFullscreen();
		}else if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
		}else if (document.webkitExitFullscreen) {
			document.webkitExitFullscreen();
		}
	}else{
		if(element.requestFullscreen) {
			element.requestFullscreen();
		}else if(element.msRequestFullscreen) {
			element.msRequestFullscreen();
		}else if(element.mozRequestFullScreen) {
			element.mozRequestFullScreen();
		}else if(element.webkitRequestFullscreen) {
			element.webkitRequestFullscreen();
		}
	}
}

// 对象
tool.object = {
  copy: function (obj) {
    return JSON.parse(JSON.stringify(obj));
  },
  clone: function (source) {
    if (!source && typeof source !== 'object') {
      throw new Error('error arguments', 'deepClone')
    }
    const targetObj = source.constructor === Array ? [] : {}
    Object.keys(source).forEach(keys => {
      if (source[keys] && typeof source[keys] === 'object') {
        targetObj[keys] = tool.object.clone(source[keys])
      } else {
        targetObj[keys] = source[keys]
      }
    })
    return targetObj
  }
}

// 验证器
tool.validator = {
  /**
   * 校验是否以为外链
   * @param {string} path
   * @returns {Boolean}
   */
  validExternal: function (path) {
    return /^(https?:|mailto:|tel:)/.test(path)
  },
  /**
   * 校验是否为URL
   * @param {string} url
   * @returns {Boolean}
   */
  validURL: function (url) {
    const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
    return reg.test(url)
  },
  /**
   * 校验是否小写
   * @param {string} str
   * @returns {Boolean}
   */
  validLowerCase: function (str) {
    const reg = /^[a-z]+$/
    return reg.test(str)
  },
  /**
   * 校验是否大写
   * @param {string} str
   * @returns {Boolean}
   */
  validUpperCase: function (str) {
    const reg = /^[A-Z]+$/
    return reg.test(str)
  },
  /**
   * 校验是否为字母
   * @param {string} str
   * @returns {Boolean}
   */
  validAlphabets: function (str) {
    const reg = /^[A-Za-z]+$/
    return reg.test(str)
  },
  /**
   * 校验是否为邮箱
   * @param {string} email
   * @returns {Boolean}
   */
  validEmail: function (email) {
    const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return reg.test(email)
  }
}

/* 日期格式化 */
tool.dateFormat = function (date, fmt='yyyy-MM-dd hh:mm:ss') {
	date = new Date(date)
	var o = {
		"M+" : date.getMonth()+1,                 //月份
		"d+" : date.getDate(),                    //日
		"h+" : date.getHours(),                   //小时
		"m+" : date.getMinutes(),                 //分
		"s+" : date.getSeconds(),                 //秒
		"q+" : Math.floor((date.getMonth()+3)/3), //季度
		"S"  : date.getMilliseconds()             //毫秒
	};
	if(/(y+)/.test(fmt)) {
		fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
	}
	for(var k in o) {
		if(new RegExp("("+ k +")").test(fmt)){
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
		}
	}
	return fmt;
}

/* 千分符 */
tool.groupSeparator = function (num) {
	num = num + '';
	if(!num.includes('.')){
		num += '.'
	}
	return num.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
		return $1 + ',';
	}).replace(/\.$/, '');
}

tool.dataToTree = function (arr) {
  //先检测是不是数组类型
  if (!Array.isArray(arr)) {
    return [];
  }
  // JS的对象就是hash表
  const obj = {};
  arr.forEach((item) => {
    obj[item.id] = item;
  });
  const targetArr = [];
  arr.forEach((item) => {
    const parent = obj[item.parentId];//有pId就说明他有父亲，找到他的父亲parent
    if (parent) {  //如果他有父亲，就给他添加children属性
      parent.children = parent.children || [];
      parent.children.push(item);
    } else {  //他没有父亲，就把当前项push进去（顶层）
      targetArr.push(item);
    }
  });
  return targetArr;
}

/* 常用加解密 */
tool.crypto = {
	//MD5加密
	MD5(data){
		return CryptoJS.MD5(data).toString()
	},
	//BASE64加解密
	BASE64: {
		encrypt(data){
			return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data))
		},
		decrypt(cipher){
			return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8)
		}
	},
	//AES加解密
	AES: {
		encrypt(data, secretKey, config={}){
			if(secretKey.length % 8 != 0){
				console.warn("[SCUI error]: 秘钥长度需为8的倍数，否则解密将会失败。")
			}
			const result = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(secretKey), {
				iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode[config.mode || "ECB"],
				padding: CryptoJS.pad[config.padding || "Pkcs7"]
			})
			return result.toString()
		},
		decrypt(cipher, secretKey, config={}){
			const result = CryptoJS.AES.decrypt(cipher, CryptoJS.enc.Utf8.parse(secretKey), {
				iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode[config.mode || "ECB"],
				padding: CryptoJS.pad[config.padding || "Pkcs7"]
			})
			return CryptoJS.enc.Utf8.stringify(result);
		}
	}
}

export default tool
